package com.pig.service.Impl;


import com.pig.exception.ServiceException;
import com.pig.mapper.dao.FoodMatDao;
import com.pig.mapper.dao.MenuDao;
import com.pig.mapper.dao.ProStepDao;
import com.pig.pojo.CookBook;
import com.pig.pojo.FoodMat;
import com.pig.pojo.ProStep;
import com.pig.service.MenuService;
import com.pig.util.SysResultLayui;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private FoodMatDao foodMatDao;
    @Autowired
    private ProStepDao proStepDao;
    @Override
    public SysResultLayui<CookBook> findObject(Integer page, Integer limit) {
        if(page==null||page<1)
            throw new IllegalArgumentException("当前页码值无效");
        int totla = menuDao.getCount(null);
        //int totla = menuDao.getCount(menuName);
        //if (totla<1)
        //    throw new ServiceException("查找的菜谱不存在");
        if(limit==null||limit<1)
            throw new IllegalArgumentException("当前页数值无效");
        int pageSize=limit;
        int indexSize = (page-1)*pageSize;
        List<CookBook> records = menuDao.findObject(null,indexSize,pageSize);
        //System.out.println(records);
        return new SysResultLayui<>(200,"OK",totla,records);
    }

    @Override
    public CookBook findObjectById(Integer id) {
        if (id==null)
            throw  new ServiceException("参数错误");
        CookBook cookBook =menuDao.findObjectById(id);
        //String image = cookBook.getFinishedImg();
        //int index = image.indexOf(",");
        //cookBook.setFinishedImg(image.substring(0, index));
        //System.out.println(cookBook.getFinishedImg());
        return cookBook;
    }
    @Transactional
    @Override
    public void AddCookBook(CookBook cookBook) {
        if (cookBook==null)
            throw  new ServiceException("参数错误");
        //List<FoodMat> foodMats = new ArrayList<>();
        //List<ProStep> proSteps = new ArrayList<>();
        menuDao.insertObject(cookBook);
        for (FoodMat foodMat:cookBook.getIngredient_groups()){
            foodMat.setMenuId(cookBook.getId());
            foodMatDao.insertFoodMat(foodMat);
            //foodMats.add(foodMat);
        }
        for (ProStep proStep:cookBook.getStepId()){
            proStep.setMenuId(cookBook.getId());
            proStepDao.insertProStep(proStep);
            //proSteps.add(proStep);
        }
    }
    @Transactional
    @Override
    public void deleteObjectById(Integer id) {
        if (id==null)
            throw  new ServiceException("参数错误");

        foodMatDao.deleteMenuById(id);
        proStepDao.deleteMenuById(id);
        int row = menuDao.deleteMenuById(id);
        if (row==0)
            throw  new ServiceException("删除不成功");
    }
}
